<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/16 10:25
 */

namespace App\Project\Filters;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;

abstract class FilterAbstract
{
    protected $request;

    protected $nullable = [];

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * @param $nullable
     * @return $this
     */
    public function setNullable(array $nullable)
    {
        $this->nullable = $nullable;

        return $this;
    }

    public function input()
    {
        return $this->get('input');
    }

    public function except($keys)
    {
        return $this->get('except', $keys);
    }

    public function get($method, $param = null)
    {
        $input = Arr::dot($this->request->$method($param));

        $data = [];

        $accessFields = $this->makeFieldMap();

        foreach ($input as $key => $item) {

//            if (is_null($item) || '' === $item) {
//                continue;
//            }

            if (array_key_exists($key, $accessFields)) {
                Arr::set($data, $key, $item);
            }
        }

        return $data;
    }

    protected function makeFieldMap()
    {
        $map = $this->getRootFieldsHasNoSon();

        if ($map)
            $map = array_flip($map);

        foreach ($this->getRootFieldsHasSon() as $item) {
            $map[$item] = array_flip($this->getSonFieldsForEachRoot());
        }

        return Arr::dot(array_merge($map, $this->forExtend()));
    }

    abstract protected function forExtend();

    abstract protected function getRootFieldsHasNoSon();

    abstract protected function getRootFieldsHasSon();

    abstract protected function getSonFieldsForEachRoot();
}